package mamikeji.liaowa.ui.activity.circle;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.umeng.analytics.MobclickAgent;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import mamikeji.liaowa.R;
import mamikeji.liaowa.bean.MomCircleBean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.BaseActivity;
import mamikeji.liaowa.ui.adapter.MainFragmentAdapter;
import mamikeji.liaowa.ui.fragment.mom_cirlce.Mom_CircleFragment;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;

/**
 * Created by 廉冲-android开发 on 2017/9/22.
 */
public class BabyMomCircleActivity extends BaseActivity {
    private static final String TAG = "BabyMomCircleActivity";
    private static final int TAG_CIRCLE = 1001;
    @BindView(R.id.toolbar_tab_momcircle)
    TabLayout toolbarTabMomcircle;
    @BindView(R.id.viewPager_momcircle_listdate)
    ViewPager viewPagerMomcircleListdate;
    @BindView(R.id.imageView_momcircle)
    ImageView imageViewMomcircle;

    List<MomCircleBean.DataEntity.CirclesEntity> circleTypesList = new ArrayList<>();

    Boolean bool_circle_refresh = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_babymom_circle);
        getBase();
        ButterKnife.bind(this);
        setTitleLeftImage(R.drawable.icon_fanhuibai_n_fff, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (bool_circle_refresh){
                    setResult(RESULT_OK, new Intent());
                }
                finish();
            }
        });
        setTitleName(R.string.momcircle_name);

        init();
    }

    private void init() {
        //获取分类
        getMom_FriendCircleData();

        imageViewMomcircle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivityForResult(new Intent(BabyMomCircleActivity.this, CircleTypeActivity.class) , TAG_CIRCLE);
            }
        });
    }

    /**
     * 获取宝妈朋友圈分类数据
     *
     * @return
     */
    public void getMom_FriendCircleData() {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.MOM_FC_usercode, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.MOM_FC_current, "0");
        formMap.put(HttpKey.MOM_FC_pagesize, "10");
        formMap.put(HttpKey.MOM_FC_circle_type, "0");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.GetMamCirclePage, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
//                multiStateViewMainFragmentCircle.setViewState(MultiStateView.VIEW_STATE_NOINTERNET);
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG + "getMom_FriendCircleData", response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        MomCircleBean bean = new Gson().fromJson(response, MomCircleBean.class);

                        circleTypesList.clear();
                        circleTypesList = bean.getData().getCircles();

                        if (circleTypesList != null && circleTypesList.size() > 0) {
                            List<Fragment> fragments = new ArrayList<>();
                            List<String> stringList = new ArrayList<String>();

                            stringList.add("全部");
                            fragments.add(Mom_CircleFragment.Instance("0", true));
                            for (int i = 0; i < circleTypesList.size(); i++) {
                                fragments.add(Mom_CircleFragment.Instance(circleTypesList.get(i).getType_id()+"", false));
                                stringList.add(circleTypesList.get(i).getType_name());
                            }

                            MainFragmentAdapter mFragmentAdapteradapter =
                                    new MainFragmentAdapter(BabyMomCircleActivity.this, getSupportFragmentManager(), fragments , stringList);
                            viewPagerMomcircleListdate.setAdapter(mFragmentAdapteradapter);
                            viewPagerMomcircleListdate.setCurrentItem(0);

                            viewPagerMomcircleListdate.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener
                                    (toolbarTabMomcircle));
                            toolbarTabMomcircle.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener
                                    (viewPagerMomcircleListdate));

                            toolbarTabMomcircle.setupWithViewPager(viewPagerMomcircleListdate);
                            toolbarTabMomcircle.setTabMode(TabLayout.MODE_SCROLLABLE);

//                            multiStateViewMainFragmentCircle.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        } else {
//                            multiStateViewMainFragmentCircle.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                        }
                    } else {
//                        multiStateViewMainFragmentCircle.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public View getTabView(int position) {
        View view = LayoutInflater.from(this).inflate(R.layout.tab_item, null);
        TextView tv_item = (TextView) view.findViewById(R.id.textView_tab_name);
        tv_item.setText(circleTypesList.get(position).getType_name());
        return view;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == TAG_CIRCLE) {
                //获取首页朋友圈
                getMom_FriendCircleData();
                bool_circle_refresh = true;
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if(bool_circle_refresh){
                setResult(RESULT_OK, new Intent());
            }
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("宝妈圈");
        MobclickAgent.onResume(this);       //开始统计时长
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("宝妈圈");
        MobclickAgent.onPause(this);       //结束统计时长
    }
}